//
//  SetStaffRoomTimeController.m
//  QRMaster
//
//  Created by myApple on 16/5/20.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "SetStaffRoomTimeController.h"
#import "StaffTimeChooseView.h"
#import "AssignFloorTimeModel.h"
#import "SetStaffFloorTimeCell.h"
#import "RequestNetWork.h"

@interface SetStaffRoomTimeController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,UIGestureRecognizerDelegate,StaffTimeChooseViewDelegate>
{
    UITableView * floorTabelView;
    NSArray * floorDataArray;
    NSArray * weekData;
    
    UIImageView * submitImageView;
    UILabel * submitLabel;
    UIButton * backBtn;
    
    UILabel * bottomLabel;
    UIImageView * buttomRightImgView;
    UILabel * bottomSelectTimeLabel;
    BOOL isSign;//单选还是多选
    NSMutableArray * selectFloorId;
    UIView * backView;
    NSString * timeIdString;
    StaffTimeChooseView * staffTimeView;
    
    NSIndexPath * beforeIndexPath;//点击的前一个cell
}

@end

@implementation SetStaffRoomTimeController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom ;
        isSign = YES;//默认单选
        selectFloorId = [[NSMutableArray alloc]init];
        weekData = @[NSLocalizedString(@"Sunday", nil),NSLocalizedString(@"Monday", nil),NSLocalizedString(@"Tuesday", nil),NSLocalizedString(@"Wednesday", nil),NSLocalizedString(@"Thursday", nil),NSLocalizedString(@"Friday", nil),NSLocalizedString(@"Saturday", nil)];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"按楼层分配";
    [self prepareNavBtn];
    [self prepareTabelView];
    [self prepareBottomView];
    [self prepareTimeView];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    submitImageView.hidden = NO;
    backBtn.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    submitImageView.hidden = YES;
    backBtn.hidden = YES;
}

-(void)setFloorInfoArray:(NSMutableArray *)FloorInfoArray
{
    _FloorInfoArray = FloorInfoArray;
    floorDataArray = _FloorInfoArray;
}

-(void)prepareNavBtn
{
    submitImageView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH - 66, 2, 50, 40)];
    submitImageView.userInteractionEnabled = NO;
    UITapGestureRecognizer * submitTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(makeSure)];
    [submitImageView addGestureRecognizer:submitTap];
    [self.navigationController.navigationBar addSubview:submitImageView];
    
    submitLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 50, 20)];
    submitLabel.text = NSLocalizedString(@"authenSubmit",@"完成");
    submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
    submitLabel.font = [UIFont systemFontOfSize:15.0];
    submitLabel.textAlignment = NSTextAlignmentRight;
    [submitImageView addSubview:submitLabel];
    
    float x = 0;
    float y = 0;
    float width = 56;
    float height = 40;
    backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(x, y, width, height);
    [backBtn addTarget:self action:@selector(userBack) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:backBtn];
}

#pragma mark --------------tableview
-(void)prepareTabelView
{
    float x = 0;
    float y = 5;
    float width = UI_SCREEN_WIDTH;
    float height = UI_SCREEN_HEIGHT - 64 - y - 44;
    
    floorTabelView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    floorTabelView.dataSource = self;
    floorTabelView.delegate = self;
    floorTabelView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:floorTabelView];
}

#pragma mark ----------底部view及其操作
-(void)prepareBottomView
{
    float x = 0;
    float y = UI_SCREEN_HEIGHT - 44 - 64;
    float width = UI_SCREEN_WIDTH;
    float height = 44;
    UIView * buttomView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    buttomView.backgroundColor = UIColorFromRGB(0xf5f5f5);
    [self.view addSubview:buttomView];
    
    y = 0;
    width = 80;
    height = 44;
    UIImageView * bottomLeftImgView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    bottomLeftImgView.userInteractionEnabled = YES;
    UITapGestureRecognizer * leftTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttomLeftClick)];
    [bottomLeftImgView addGestureRecognizer:leftTap];
    [buttomView addSubview:bottomLeftImgView];
    
    x = 16;
    y = 12;
    width = 60;
    height = 20;
    bottomLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    bottomLabel.font = [UIFont systemFontOfSize:14.0];
    bottomLabel.text = @"选择";
    [bottomLeftImgView addSubview:bottomLabel];
    
    x = UI_SCREEN_WIDTH/ 2.0;
    width = x;
    height = 44;
    y = 0;
    buttomRightImgView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    buttomRightImgView.userInteractionEnabled = YES;
    buttomRightImgView.hidden = YES;
    UITapGestureRecognizer * rightTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttomRightClick)];
    [buttomRightImgView addGestureRecognizer:rightTap];
    [buttomView addSubview:buttomRightImgView];
    
    x = 0;
    y = 12;
    width = UI_SCREEN_WIDTH / 2.0 - 16.0;
    height = 20;
    bottomSelectTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    bottomSelectTimeLabel.text = @"分配开门周期";
    bottomSelectTimeLabel.font = [UIFont systemFontOfSize:14.0];
    bottomSelectTimeLabel.textAlignment = NSTextAlignmentRight;
    bottomSelectTimeLabel.textColor = UIColorFromRGB(0x00aff0);
    [buttomRightImgView addSubview:bottomSelectTimeLabel];
    
}

-(void)buttomLeftClick
{
    buttomRightImgView.hidden = !buttomRightImgView.hidden;
    if (buttomRightImgView.hidden) {
        bottomLabel.text = @"选择";
        isSign = YES;
        [selectFloorId removeAllObjects];
        [floorTabelView reloadData];
        [self judgeSelect];
    }
    else
    {
        bottomLabel.text = @"取消";
        isSign = NO;
    }
}

-(void)buttomRightClick
{
    if (backView.hidden) {
        backView.hidden = NO;
    }
}

-(void)prepareTimeView
{
    float x = 0;
    float y = 0;
    float width = UI_SCREEN_WIDTH;
    float height = UI_SCREEN_HEIGHT;
    backView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    backView.backgroundColor = [UIColor clearColor];
    backView.hidden = YES;
    UITapGestureRecognizer * cancelTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelTimeView)];
    cancelTap.delegate = self;
    [backView addGestureRecognizer:cancelTap];
    [self.view addSubview:backView];
    
    y = UI_SCREEN_HEIGHT - _managerTimeArray.count * 56 - 64 - 0.5;
    height = _managerTimeArray.count * 56 + 0.5;
    staffTimeView = [[StaffTimeChooseView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    staffTimeView.totalTimeArray = _managerTimeArray;
    staffTimeView.delegate = self;
    [backView addSubview:staffTimeView];
    
}

-(void)cancelTimeView
{
    if (!backView.hidden) {
        backView.hidden = YES;
    }
}

#pragma mark -- 解决tableview中手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

#pragma mark ------------staffTimeViewDelegate
-(void)selectTimeId:(NSString *)timeId
{
    timeIdString = timeId;
    [self judgeSelect];
}

#pragma mark ---------tableviewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return floorDataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AssignFloorTimeModel * model = floorDataArray[indexPath.row];
    SetStaffFloorTimeCell * cell = [SetStaffFloorTimeCell cellWithTableView:tableView];
    cell.accessoryType = UITableViewCellAccessoryNone;
    [cell setData:model];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    AssignFloorTimeModel * model = floorDataArray[indexPath.row];
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!isSign) {
        if (cell.accessoryType == UITableViewCellAccessoryCheckmark ) {
            cell.accessoryType = UITableViewCellAccessoryNone;
            [selectFloorId removeObject:model.floorId];
        }
        else
        {
            [selectFloorId addObject:model.floorId];
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
    }
    else
    {
        [selectFloorId removeAllObjects];
        if (beforeIndexPath.row == indexPath.row) {
            //如果点击同一个
            if (cell.accessoryType == UITableViewCellAccessoryNone) {
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
                [selectFloorId addObject:model.floorId];
            }
            else
            {
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
        }
        else
        {
            UITableViewCell * beforeCell = [tableView cellForRowAtIndexPath:beforeIndexPath];
            beforeCell.accessoryType = UITableViewCellAccessoryNone;
            [selectFloorId addObject:model.floorId];
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        if (selectFloorId.count > 0) {
            backView.hidden = NO;
        }
    }
    [self judgeSelect];
    beforeIndexPath = indexPath;
}
#pragma mark --------提交时间周期
-(void)makeSure
{
    if (selectFloorId.count < 1) {
        [PromptInfoView showMessage:NSLocalizedString(@"chooseRoomPlease", nil) superView:self.view];
        return;
    }
    if ([self IsHaveNetwork]) {
        return;
    }
    NSMutableString * floorIdString = [[NSMutableString alloc]init];
    for (NSString * FloorId in selectFloorId) {
        [floorIdString appendString:FloorId];
        [floorIdString appendString:@","];
    }
    NSString * floorString = [floorIdString substringToIndex:[floorIdString length]-1];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:[QRSingleton sharedQRSingleton].communityId forKey:@"communityId"];
    [postDict setValue:_staffId forKey:@"userId"];
    [postDict setValue:floorString forKey:@"floorIds"];
    [postDict setValue:timeIdString forKey:@"timeIds"];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [self startWaiting:nil color:nil addToView:self.view];
    __weak SetStaffRoomTimeController * weakSelf = self;
    [rnw initWithPath:POST(EDITSTAFFFLOORTIME) params:postDict block:^(id downLoadData, id error)
     {
         [weakSelf stopWaiting];
         if (downLoadData) {
             [PromptInfoView showMessage:NSLocalizedString(@"addTimeSuccess", nil) superView:self.view];
             [self.navigationController popViewControllerAnimated:YES];
         }
         else
         {
             [PromptInfoView showMessage:[error objectForKey:@"info"]];

         }
     }
     ];

}


#pragma mark ----------用户自定义返回键
-(void)userBack
{
    if ([self judgeSelect]) {
        UIAlertView * alterView = [[UIAlertView alloc]initWithTitle:nil message:NSLocalizedString(@"shouldSave", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"notSave", nil) otherButtonTitles:NSLocalizedString(@"save", nil), nil];
        [alterView show];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self makeSure];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(BOOL)judgeSelect
{
    if (selectFloorId.count > 0 && timeIdString.length > 0) {
        submitImageView.userInteractionEnabled = YES;
        submitLabel.textColor = UIColorFromRGB(0x7dc234);
        return YES;
    }
    else
    {
        submitImageView.userInteractionEnabled = NO;
        submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
        return NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
